<template>

    <div class="coach-page page">
        <div class="content">
            <PlatformCrumb back="教案详情">
                <button class="coach-blue" @click="saveImage('pop3',dataForm.name)">下载教程</button>
            </PlatformCrumb>
            <div class="coach-lesson-con">
                <!--                <p class="lesson-con-title">{{dataForm.name}}</p>-->
                <el-form size="medium" class="detailForm" label-width="120px" :model="dataForm" :rules="rules"
                         ref="ruleForm">
                    <div id="pop3" ref="pop3">
                        <el-row :gutter="20">
                            <el-form-item prop="name">
                                <el-col :span="24" class="titles">
                                    <el-input placeholder="请输入教案标题" class="w100" v-model="dataForm.name"/>
                                </el-col>
                            </el-form-item>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="教练员" prop="coachName">
                                    <el-input v-model="dataForm.coachName"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="日期" prop="time">
                                    <el-date-picker
                                            v-model="dataForm.time"
                                            type="date"
                                            value-format="timestamp"
                                            placeholder="选择日期">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24" prop="theme">
                                <el-form-item label="训练主题">
                                    <el-input v-model="dataForm.theme"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="8">
                                <el-form-item label="器材" prop="equipment">
                                    <el-input v-model="dataForm.equipment"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="训练时长" prop="duration">
                                    <el-input type="number" placeholder="请输入训练时长" v-model="dataForm.duration">
                                        <template slot="append">分钟</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="出席人数" prop="count">
                                    <el-input v-model="dataForm.count">
                                        <template slot="append">人</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="组织方法" prop="method">
                                    <el-input v-model="dataForm.method "/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item prop="practice" label="练习要求，要点">
                                    <el-input v-model="dataForm.practice"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="练习图" prop="imgs">
                                    <div class="uploadimg">
                                        <img v-if="dataForm.imgs" :src="dataForm.imgs|filtersImg" alt="">
                                        <div class="upload2input">
                                            <el-upload
                                                    ref='upload'
                                                    :action='imgupload'
                                                    class="upload-demo"
                                                    accept="image/jpeg"
                                                    :show-file-list="false"
                                                    name="file"
                                                    :on-success="handleAvatarSuccess"
                                                    multiple>
                                                <i class="el-icon-plus avatar-uploader-icon"></i>
                                                <div class="el-upload__text">点击上传</div>
                                            </el-upload>
                                            <p style="color: #999999">仅支持JPG格式</p>
                                        </div>
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>

                    </div>
                    <el-form-item>
                        <el-button type="primary" @click="checkForm" v-if="!courseId">添加教案</el-button>
                        <el-button type="primary" @click="checkForm" v-else>修改教案</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<style>
    .el-upload {
        width: 98px;
        height: 98px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        border: 1px dashed #d9d9d9;
    }

    .upload-con .avatar-uploader-icon {
        height: 30px !important;
        width: 30px !important;
        line-height: 30px !important;
    }

    .el-upload-dragger {
        width: 98px !important;
        height: 98px !important;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

    .upload-video .el-upload {
        width: 100px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: linear-gradient(0deg, rgba(251, 251, 251, 1), rgba(244, 244, 244, 1), rgba(255, 255, 255, 1));
        border: 1px solid rgba(227, 227, 227, 1);
    }

    .uploadimg {
        display: flex;
        justify-content: flex-start;
        align-items: flex-end;
    }

    .uploadimg img {
        margin-right: 20px;
        width: 200px;
        height: 200px;
    }

    .upload2input {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

    .titles {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 50px;
        margin-top: 40px;
    }

    .titles input {
        text-align: center;
        width: 100%;

        max-width: 100% !important;
    }

    .el-button--medium {
        padding: 5px 20px;
    }

    .w100 {
        width: 100%;
    }
</style>
<script>
    import {mapActions} from 'vuex'
    import {isNumber} from '../../utils/utils'
    import PlatformCrumb from "@/components/PlatformCrumb.vue";
    import {basefile, imgupload} from '@/config/env.js';
    import {teachingPlanedit, teachingPlanadd, teachingPlanget} from '../../api/api/coach.js';
    import html2canvas from 'html2canvas'
    export default {
        components: {
            PlatformCrumb,
        },
        data() {
            return {
                key: "value",
                dataForm: {
                    time: '',
                    practice: '',
                    method: '',
                    count: '',
                    equipment: '',
                    theme: '',
                    duration: '',
                    imgs: '',
                    name: '',
                    coachId: sessionStorage.getItem('statusId') ? parseInt(sessionStorage.getItem('statusId')) : 0,
                    coachName: sessionStorage.getItem('nikename') ? sessionStorage.getItem('nikename') : 0,
                },
                rules: {
                    name: [
                        {required: true, message: '请输入教案标题', trigger: 'blur'},
                    ],
                    coachName: [
                        {required: true, message: '请输入教练员名称', trigger: 'blur'},
                    ], method: [
                        {required: true, message: '请输入组织方法', trigger: 'blur'},
                    ], imgs: [
                        {required: true, message: '请上传练习图片', trigger: 'blur'},
                    ], name: [
                        {required: true, message: '请输入教案标题', trigger: 'blur'},
                    ], duration: [
                        {required: true, message: '请输入训练时长', trigger: 'blur'},
                    ], count: [
                        {required: true, message: '请输入出席人数', trigger: 'blur'},
                    ], time: [
                        {required: true, message: '请选择训练日期', trigger: 'blur'},
                    ],
                },
                imgupload: imgupload,
            }
        },

        computed: {
            courseId() {
                return this.$route.query.id ? this.$route.query.id : 0
            }
        },

        methods: {
            dataURLToBlob(dataurl) {
                let arr = dataurl.split(',');
                let mime = arr[0].match(/:(.*?);/)[1];
                let bstr = atob(arr[1]);
                let n = bstr.length;
                let u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new Blob([u8arr], {type: mime});
            },
            /*保存图片的方法（即按钮点击触发的方法）
              第一个参数为需要保存的div的id名
              第二个参数为保存图片的名称 */
            saveImage(divText, imgText) {
                window.scrollTo(0, 0);
                let canvasID = this.$refs[divText];
                let that = this;
                let a = document.createElement('a');
                html2canvas(canvasID).then(canvas => {
                    let dom = document.body.appendChild(canvas);
                    dom.style.display = 'none';
                    a.style.display = 'none';
                    document.body.removeChild(dom);
                    let blob = that.dataURLToBlob(dom.toDataURL('image/png'));
                    a.setAttribute('href', URL.createObjectURL(blob));
                    //这块是保存图片操作  可以设置保存的图片的信息
                    a.setAttribute('download', imgText + '.png');
                    document.body.appendChild(a);
                    a.click();
                    URL.revokeObjectURL(blob);
                    document.body.removeChild(a);
                });
            },
            ...mapActions('myCourse', [
                'fetchCourseDetail',
                'addCourse',
                'editCourse'
            ]),
            handleAvatarSuccess(res, file) {
                console.log(res);
                console.log(file);
                this.dataForm.imgs = res.data.path
            },
            checkForm() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        if (this.courseId) {
                            this.onEdit()
                        } else {
                            this.onAdd()
                        }

                    } else {
                        return false
                    }
                })
            },

            getDetail() {
                const id = this.courseId
                this.fetchCourseDetail({id}).then(res => {
                    const {code, data} = res
                    if (code === 200) {
                        this.dataForm = data || {}
                        console.log(this.dataForm)
                    }
                })
            },

            onAdd() {
                this.setData()
                this.addCourse(this.dataForm).then(res => {
                    const {code, message} = res
                    if (code === 200) {
                        this.$message({
                            message: message,
                            type: 'success'
                        })
                        this.$router.push('/coach/mycourse')
                    }
                })
            },

            setData() {
                Number(this.dataForm.count)
                Number(this.dataForm.duration)
                Number(this.dataForm.time)
            },

            onEdit() {
                this.setData()
                this.editCourse(this.dataForm).then(res => {
                    const {code, message} = res
                    if (code === 200) {
                        this.$message({
                            message: message,
                            type: 'success'
                        })
                        this.$router.push('/coach/mycourse')
                    }
                })
            }
        },

        created() {
            if (this.courseId) {
                this.getDetail()
            }
        },
        filters: {
            filtersImg: function (img) {
                return basefile + img
            },
        },
    }
</script>

<style scoped>
    @import url("P-coach.css");

    .detailForm {
        width: 900px;
        margin: 0 auto;
    }
</style>
